<?php

namespace App\Http\Controllers;

use App\Http\Requests\AccountClueRequest;
use App\Http\Requests\AccountStoreRequest;
use App\Http\Requests\AccountUpdateRequest;
use App\Http\Resources\AccountResource;
use App\Models\Account;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class AccountController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return \Illuminate\Http\Resources\Json\JsonResource
     */
    public function index(Request $request)
    {
        $pageSize = $request->get('page_size', 25);
        $data     = Account::paginate($pageSize);
        return AccountResource::collection($data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  AccountStoreRequest $request
     * @return \Illuminate\Http\Resources\Json\JsonResource
     */
    public function store(AccountStoreRequest $request)
    {
        $data    = $request->all();
        $account = Account::create($data);

        return new AccountResource($account);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  AccountUpdateRequest $request
     * @param  \App\Models\Account  $account
     * @return \Illuminate\Http\Resources\Json\JsonResource
     */
    public function update(AccountUpdateRequest $request, Account $account)
    {
        $data = $request->all();
        $account->update($data);
        return new AccountResource($account);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @throws (a)
     * @param  \App\Models\Account $account
     * @return \Illuminate\Http\Response
     */
    public function destroy(Account $account)
    {
        $account->delete();
        return response(null, Response::HTTP_NO_CONTENT);
    }

    public function signature(Account $account, AccountClueRequest $request)
    {
        $start_time = $request->input('start_time');
        $end_time   = $request->input('end_time');
        $url        = '/crm/v2/openapi/pull-clues/';

        $timestamp = time();
        $string    = "$url?start_time=$start_time&end_time=$end_time $timestamp";
        $sign      = signature($account->key, $string);


        return $this->responseSuccess([
            'sign'      => $sign,
            'token'     => $account->token,
            'timestamp' => $timestamp
        ]);
    }

    public function clues(Account $account, AccountClueRequest $request)
    {
        $start_time = $request->input('start_time');
        $end_time   = $request->input('end_time');
        $page       = $request->input('page', 1);
        $page_size  = $request->input('page_size', 10);

        $data = crmPullClues($account, $start_time, $end_time, $page, $page_size);

//        if ((int)$data['count'] > $page_size) {
//            $data = crmPullClues($account, $start_time, $end_time, $page, $data['count']);
//        }
        return $data;
    }
}
